<script lang="ts" setup>
import { ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm, z } from '#/adapter';
import { getRolesNoSuperApi } from '#/api/core/role';
import { saveUser } from '#/api/core/user';
import { $t } from '#/locales';

defineOptions({
  name: 'UserDrawer',
});

// 定义 props 参数
const props = defineProps<{
  onSave: () => void;
  roles: string[];
}>();

// 角色选项
const roleOptions = ref<{ label: string; value: string }[]>([]);

// 获取角色列表
async function loadRoles() {
  try {
    const res = await getRolesNoSuperApi({
      page: 1,
      pageSize: 100,
    });
    if (res.items?.length) {
      roleOptions.value = res.items.map((role: any) => ({
        label: role.name,
        value: String(role.id),
      }));
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
}

// 组件挂载时加载角色列表
loadRoles();

// 1. 先定义 UserRole 接口
interface UserRole {
  id: number;
  userId: number;
  roleId: number;
  roleName: string;
  createTime: number;
  updateTime: number;
}

// 2. 再定义 UserType 接口
interface UserType {
  id: string;
  username: string;
  realName: string;
  email: string;
  phone: string;
  deptId: number;
  roles: UserRole[];
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        type: 'hidden',
      },
      fieldName: 'id',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('user.drawer.form.username.placeholder'),
      },
      fieldName: 'username',
      label: $t('user.drawer.form.username.label'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('user.drawer.form.realName.placeholder'),
      },
      fieldName: 'realName',
      label: $t('user.drawer.form.realName.label'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('user.drawer.form.email.placeholder'),
        type: 'email',
      },
      fieldName: 'email',
      label: $t('user.drawer.form.email.label'),
      rules: z.string().email($t('user.drawer.form.email.required')),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('user.drawer.form.phone.placeholder'),
      },
      fieldName: 'phone',
      label: $t('user.drawer.form.phone.label'),
    },
    {
      component: 'Select',
      componentProps: {
        options: roleOptions,
        placeholder: $t('user.drawer.form.roles.placeholder'),
        mode: 'multiple',
        allowClear: true,
        fieldNames: {
          label: 'label',
          value: 'value',
        },
      },
      fieldName: 'roles',
      label: $t('user.drawer.form.roles.label'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        type: 'hidden',
      },
      fieldName: 'deptId',
    },
  ],
  showDefaultActions: false,
});

async function onSubmit(values: Record<string, any>) {
  try {
    if (!values.deptId) {
      values.deptId = '1';
    }
    if (!Array.isArray(values.roles)) {
      values.roles = values.roles ? [values.roles] : [];
    }
    await saveUser(values);
  } catch (error: any) {
    console.error('保存用户失败:', error);
    throw new Error(error.message || '提交失败');
  }
}

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    const isValid = await formApi.validate();
    if (isValid.valid) {
      try {
        const values = formApi.form.values;
        await formApi.submitForm();
        drawerApi.close();
        message.success(
          values.id
            ? $t('common.action.editSuccess')
            : $t('common.action.addSuccess'),
        );
        props.onSave();
      } catch (error: any) {
        console.error('提交失败:', error);
        message.error(error.message || $t('common.submit.failed'));
      }
    } else {
      message.error($t('common.form.required'));
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values = drawerApi.getData<UserType>();
      if (values) {
        if (values.roles) {
          const roleIds = values.roles.map((role) => String(role.roleId));
          formApi.setValues({
            ...values,
            roles: roleIds,
          });
        } else {
          formApi.setValues({
            ...values,
            roles: [],
          });
        }
      }
    }
  },
});

watch(
  props.roles,
  (newRoles) => {
    formApi.setValues({ roles: newRoles });
  },
  { immediate: true },
);
</script>

<template>
  <Drawer
    :title="
      formApi.form.values?.id
        ? $t('user.drawer.title.edit')
        : $t('user.drawer.title.add')
    "
  >
    <Form />
  </Drawer>
</template>
